﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="edit.aspx.cs" Inherits="OpenRAMS.Maintenance.edit" %>
<%@ Import Namespace="OpenRAMS.Model" %>
<script runat="server">
    void btnSubmitLog_Click(Object sender, EventArgs e)
    {
        
        //Verify integrity of input data
        if (txtLogTitle.Text == "" || txtLogTitle.Text == " " || txtLogTitle.Text == "Type title here" || txtLogDesc.Text == "" || txtLogDesc.Text == " " || txtLogDesc.Text == "Type log entry here.")
        {
            lblError.Visible = true;
            lblError.Text = "Error, missing content. (Did you click Submit by mistake?)";
        }
        else
        {
            int numHours = -1;
            try
            {
                numHours = Convert.ToInt32(txtTimeTaken.Text);
            }
            catch
            {
                lblError.Visible = true;
                lblError.Text = "Error, invalid number of hours";
            }
            if (numHours < 0)
            {
                lblError.Visible = true;
                lblError.Text = "Error, invalid number of hours";
            }
            else
            {
                //export form data
                WorkTicketLog newWtLog = new WorkTicketLog();
                newWtLog.workTicketLogLinkID = Convert.ToInt32(Request.QueryString["wtID"].ToString());
                newWtLog.workTicketLogTimeTakenHours = numHours;
                newWtLog.workTicketLogCreator = User.Identity.Name.ToString();
                newWtLog.workTicketLogCategory = listCategories.SelectedValue;

                //Escape apostrophes, as their use can break SQL queries
                String titleFix = txtLogTitle.Text;
                titleFix = titleFix.Replace("'", @"''");
                newWtLog.workTicketLogTitle = titleFix;

                String descFix = txtLogDesc.Text;
                descFix = descFix.Replace("'", @"''");
                descFix = descFix.Replace(Environment.NewLine, "<br/>");
                newWtLog.workTicketLogDesc = descFix;
                

                //..and now attempt to save it
                int trySave = newWtLog.Save();

                if (trySave < 0)
                {
                    lblError.Visible = true;
                    lblError.Text = "Error: Save failed.";
                }
                
            }
        }
        
    }

    void btnBackFromLog_Click(Object sender, EventArgs e)
    {
        Response.Redirect("Maintenance.aspx");
    }

</script>

<!DOCTYPE html />

<%
    //Grab work ticket ID from URL parameter (if it isn't present, jump back to staff portal)
    String workTicketRequest = "";
    try
    {
        workTicketRequest = Request.QueryString["wtID"].ToString();
    }
    catch { Response.Redirect("Maintenence.aspx"); }

    //Verifying that the parameter sent is an integer value
    int test = -1;
    try { test = Convert.ToInt32(workTicketRequest); }
    catch { Response.Redirect("Maintenance.aspx"); }  //if someone's entered something funky in URL bar, send them back again

    //also verifying user has the right to access this work ticket (must have either created it or have it allocated to them)
    WorkTicket wtTest = new WorkTicket();
    wtTest.Load(test);
    if (User.Identity.Name.ToString() != wtTest.workTicketCreator && User.Identity.Name.ToString() != wtTest.workTicketAllocatedTo)
    {
        Response.Redirect("Maintenance.aspx");
    }

    refNo.Text = Convert.ToString(wtTest.workTicketID);
    wtTitle.Text = wtTest.workTicketTitle;
    wtDesc.Text = "\"" + wtTest.workTicketDesc + "\"";

    UserRecord creator = new UserRecord();
    creator.Load(wtTest.workTicketCreator);
    tickCreator.Text = creator.userFirstName + " " + creator.userSecondName;

    String approved = " (";
    if (wtTest.workTicketApprovalStatus)
    {
        approved += "Approved)";
    }
    else
    {
        approved += "Pending Approval)";
    }

    wtStatus.Text = approved;

    tickCreatedDate.Text = wtTest.createdTimeStamp.ToString("ddd dd MMMM yyyy HH:mm:ss");
    
 %>

<html>
<head id="Head1" runat="server">
    <title>OpenRAMS - Work Ticket Details</title>
    <link rel="Stylesheet" type="text/css" href="../Include/default.css" />
</head>
<body>
<table class="tableDefault" align="center" width="90%">
<tr><td>
<div class="tableBody">
    <form id="form1" runat="server">
    <table width="100%">
        <tr><td><div class="tableTitle" align="center">View Work Ticket</div></td></tr>
        <tr>
        <td>
        <table align="right">
        <tr>
        <td><b>Ref No:</b> </td><td><asp:Label ID="refNo" runat="server" /></td>
        <td><b>Created by:</b> </td><td><asp:Label ID="tickCreator" runat="server" /></td>
        <td><b>Date:</b></td><td><asp:Label ID="tickCreatedDate" runat="server" /> </td>
        </tr>
        </table></td>
        </tr>
        <tr><td>
        <asp:Label ID="wtTitle" runat="server" Font-Bold="true" />
        <asp:Label ID="wtStatus" runat="server" />
        </td></tr>
        <tr><td>
        <i>
        <asp:Label ID="wtDesc" runat="server" Font-Italic="true" />
        </i>
        </td></div></tr>
        <tr><td><hr /></td></tr>
        <%
            //This code-section outputs all logs related to this ticket in chronological order   
            WorkTicketLogs logList = new WorkTicketLogs();
            logList.Populate(Convert.ToInt32(Request.QueryString["wtID"]));
            List<WorkTicketLog> logs = logList.getWorkTicketLogList();
            
            //Ensure that all records are in chronological order
            //arrange bookings so most recently created ticket appears first
            logs.Sort(delegate(WorkTicketLog a, WorkTicketLog b)
            {
                int x = a.workTicketLogTime.CompareTo(b.workTicketLogTime);
                if (x != 0) return x;
                else return a.workTicketLogTime.CompareTo(b.workTicketLogTime);
            });

            if (logs.Count() > 0)
            {
                foreach (WorkTicketLog log in logs)
                {
                    Response.Write("<tr><td>");
                    Response.Write("<table width=\"100%\"><tr><td>");
                    Response.Write("<b>" + log.workTicketLogTitle + "</b> ");
                    Response.Write("- <i>");
                    
                    UserRecord wTickCreator = new UserRecord();
                    wTickCreator.Load(log.workTicketLogCreator);

                    Response.Write(wTickCreator.userFirstName + " " + wTickCreator.userSecondName + "</i> ");
                    Response.Write("(" + log.workTicketLogCategory + ")");
                    Response.Write("</td><td align=\"right\">" + log.workTicketLogTime.ToString("ddd dd MMMM yyyy HH:mm:ss"));

                    Response.Write("</td></tr><tr><td>");
                    Response.Write("<i>\"" + log.workTicketLogDesc + "\"</i>");
                    Response.Write("</td></tr><tr><td>");

                    if (log.workTicketLogTimeTakenHours < 1)
                    {
                        decimal minutes = log.workTicketLogTimeTakenHours * 60;
                        int output = Convert.ToInt32(minutes);

                        if (minutes > 1)
                        {
                            Response.Write("Work hours: " + output + " minutes");
                        }
                    }
                    else
                    {
                        Response.Write("Work hours: " + Math.Round(log.workTicketLogTimeTakenHours,1) + " hours");
                    }
                    
                    Response.Write("</td></tr></table>");
                    Response.Write("</td></tr>");
                    Response.Write("<tr><td><hr /></td></tr>");
                }
            }
            else
            {
                //if there aren't any log entries, display something friendly
                Response.Write("<tr><td><i>No log entries have been created yet.</i></td></tr>");
            }   
        %>
        <tr>
        <td>
            <table width="100%">
            <tr><td align="center"><div class="tableTitle">Add Log Entry</div></td></tr>
            <tr><td>
            <table>
            <tr>
            <td>Category: </td>
            <td>
            <asp:DropDownList ID="listCategories" runat="server" DataSourceID="SqlDataSource1" 
                    DataTextField="txtWorkCategory" DataValueField="txtWorkCategory" >
                <asp:ListItem Selected="True">Question</asp:ListItem>
                <asp:ListItem>Answer</asp:ListItem>
                <asp:ListItem>On Hold</asp:ListItem>
                <asp:ListItem>Complete</asp:ListItem>
                <asp:ListItem>Accepted</asp:ListItem>
                </asp:DropDownList>
                <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
                    ConnectionString="<%$ ConnectionStrings:openramsConnectionString2 %>" 
                    SelectCommand="SELECT [txtWorkCategory] FROM [tblWorkCategories]">
                </asp:SqlDataSource>
            </td>
            <td>Estimated time taken (hours):</td>
            <td>
            <asp:TextBox ID="txtTimeTaken" runat="server" TextMode="Number" Text="0" MaxLength="5" />
            </td>
            <td>
            <asp:Label ID="lblError" runat="server" Visible="false" ForeColor="Red" />
            </td>
            </tr>
            </table>
            </td></tr>
            <tr><td><asp:TextBox ID="txtLogTitle" runat="server" width="100%" Text="Type title here" MaxLength="49"/></td></tr>
            <tr><td>
            <asp:TextBox ID="txtLogDesc" runat="server" TextMode="MultiLine" width="100%" 
                    Height="100px" Text="Type log entry here." MaxLength="149"/>
            </td></tr>
            <table width="100%"><tr>
            <td width="50%"><asp:Button ID="btnSubmitLog" runat="server" Text="Submit" Width="100%" OnClick="btnSubmitLog_Click"/> </td>
            <td width="50%"><asp:Button ID="btnBackFromLog" runat="server" Text="Back" Width="100%" OnClick="btnBackFromLog_Click"/></td>
            </tr>
            </table>
            </tr>
            </table>
        </td>
        </tr>
    
    </form>
    </td>
    </tr>
    <tr>
    <td><div class="footer">
    <% 
        Response.WriteFile(Server.MapPath("~/Include/footer.txt"));
    %>
    </div></td>
    </tr>
    </table>
</body>
</html>
